package com.yl.common.jwt;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import java.util.Date;
import java.util.UUID;

/**
 * @author 王庆梁
 * @datetime 2023/5/24 14:25
 * @description 类对象
 */
public class JwtTests {

    //过期时间，毫秒，24小时
    private static long tokenExpiration = 24*60*60*1000;
    //秘钥
    private static String tokenSignKey  = "wangqingliang123";


    public static void main123(String[] args) {

        String token = Jwts.builder()
                .setHeaderParam("typ","JWT") //令牌类型
                .setHeaderParam("alg","HS256") //签名算法
                .setSubject("wangqingliang-user")//令牌主题
                .setIssuer("wangqingliang")//签发人
                .setAudience("lijie")//接收者
                .setIssuedAt(new Date()) //签发时间
                .setExpiration(new Date(System.currentTimeMillis() +tokenExpiration)) //过期时间
                .setNotBefore(new Date(System.currentTimeMillis() +20 * 1000)) //20秒后可以使用
                .setId(UUID.randomUUID().toString())
                .claim("nickname","wangqingliang")
                .claim("avatar","lijie")
                .signWith(SignatureAlgorithm.HS256,tokenSignKey)//签名哈希
                .compact(); //转化成字符串
        System.out.println(token);
    }
    public static void main (String[] args) {
        String token = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJ3YW5ncWluZ2xpYW5nLXVzZXIiLCJpc3MiOiJ3YW5ncWluZ2xpYW5nIiwiYXVkIjoibGlqaWUiLCJpYXQiOjE2OTA0NzEyNTAsImV4cCI6MTY5MDU1NzY1MCwibmJmIjoxNjkwNDcxMjcwLCJqdGkiOiI4NTIzZWY5My00MjcwLTRiNGMtOWE3NC1jN2E3OWIwN2QxY2MiLCJuaWNrbmFtZSI6IndhbmdxaW5nbGlhbmciLCJhdmF0YXIiOiJsaWppZSJ9.1WZNx-SvCs1BR6lVGk9vBviWI-2Esbd28m_JGnzwc_Y";
        Jws<Claims> claimsJws = Jwts.parser().setSigningKey(tokenSignKey).parseClaimsJws(token);

        Claims claims = claimsJws.getBody();

        String subject = claims.getSubject();
        String issuer = claims.getIssuer();
        String audience = claims.getAudience();
        Date issuedAt = claims.getIssuedAt();
        Date expiration = claims.getExpiration();
        Date notBefore = claims.getNotBefore();

        String id = claims.getId();
        System.out.println(subject);
        System.out.println(issuer);
        System.out.println(audience);
        System.out.println(issuedAt);
        System.out.println(expiration);
        System.out.println(notBefore);
        System.out.println(id);;
        String nickname = (String)claims.get("nickname");
        String avatar = (String)claims.get("avatar");
        System.out.println(nickname);
        System.out.println(avatar);
    }

}
